var AddGoodsApply=function(){
		
	var addProdFunction = function() {
		var left_margin_step = 15;
		$("#addgoods").bind(
				'click',
				function() {
					var lastChildHeight=26;
					$("#sel_prod").find("div").empty();
					$("#sel_prod").attr("style","height:"+ lastChildHeight +"px");
					var myts = new Date();
					var formStr = $('#prod_filter_form').serialize();
					jQuery.ajax( {
						type : "POST",
						async : false,
						url : ebvp_context + "/other/qryGoodsClass?myts=" + myts,
						dataType : "text",
						data : "&" + formStr,
						success : function(result) {
							if(result != "[]"){
								var orgArr = eval(result);
								$("#productPicker").find(".tree_list5").empty();
								for ( var loop = 0; loop < orgArr.length; loop++) {
									var obj = orgArr[loop];
									var a = $("<a></a>").attr("href", "#").addClass(
											"category_trigger5").attr("margin", 0);								
									var inputObj = $("<input/>").val(obj.pk_marbasclass).attr("type", 
									"hidden").attr("name", "pk_marbasclass_intree");	
											
									var label = $("<label></label>").text(obj.name);
									var div = $("<div></div>")
											.addClass("tree_category5").append(a)
											.append(inputObj).append(label);												
									$("#productPicker").find(".tree_list5")
											.append(div);
								}
							}
						}				
					})
				});
				
		$("#filterProd").bind(
				'click',
				function() {
					var myts = new Date();
					var formStr = $('#prod_filter_form').serialize();
					jQuery.ajax( {
						type : "POST",
						async : false,
						url : ebvp_context + "/other/filterGoodsClass?myts=" + myts,
						dataType : "text",
						data : "&" + formStr,
						success : function(result) {
							if(result != "[]"){
								var orgArr = eval(result);
								$("#productPicker").find(".tree_list5").empty();
								for ( var loop = 0; loop < orgArr.length; loop++) {
									var obj = orgArr[loop];
									var a = $("<a></a>").attr("href", "#").addClass(
											"category_trigger5").attr("margin", 0);								
									var inputObj = $("<input/>").val(obj.pk_marbasclass).attr("type", 
									"hidden").attr("name", "pk_marbasclass_intree");	
											
									var label = $("<label></label>").text(obj.name);
									var div = $("<div></div>")
											.addClass("tree_category5").append(a)
											.append(inputObj).append(label);												
									$("#productPicker").find(".tree_list5")
											.append(div);
								}
							}
						}				
					})
				});
				
		$("#addgoods").UIDropDialog( {
			'triggerClass' : "idTreePicker",
			'content' : $("#productPicker")
		});
		
		//"close"样式(-)是已经展开时的样式
		// 控制方法：
		// 如果当前节点尚未展开(+)，此次点击触发下列行为：(1)将当前节点样式设置为已展开；(2)从后台查数据，渲染子节点;(3)将同辈的其他已展开节点及其子节点收缩，且将收缩节点的样式设置为收缩样式
		// 如果当前节点已经展开(-)，此次点击触发下列行为：(1)将当前节点的子节点收缩；(2)当前节点的样式设置为展开(-)
		$(".category_trigger5").live(
				'click',
				function() {
					var category_triggerObj=$(this);
					if(category_triggerObj.hasClass("close")){
						category_triggerObj.parent(".tree_category5").next(".children").slideUp(function(){
							category_triggerObj.removeClass("close");
						});
						return false;
					}
					
					$(this).addClass("close");
					//var pk_org_val = $(this).next("input").val();
					var pk_marbasclass = $(this).next("input").val();
					var myts = new Date();
					var formStr = $('#prod_filter_form').serialize();
					jQuery.ajax( {
						type : "POST",
						async : false,
						url : ebvp_context
								+ "/other/qryGoodsClassByPk?pk_marbasclass="
								+ pk_marbasclass  
								+ "&myts=" + myts,
						dataType : "text",
						data : "&" + formStr,
						success : function(result) {
							var orgArr = eval(result);
							var childrenDiv = $("<div></div>").addClass("children");
							var current_margin_left_size = parseInt(category_triggerObj.attr("margin")) + left_margin_step;	
							if(orgArr.length!=0){
								for ( var loop = 0; loop < orgArr.length; loop++) {
									var obj = orgArr[loop];
									var a = $("<a></a>").attr("href", "#").addClass("category_trigger5")
											.attr("style","margin-left:"+current_margin_left_size+"px")
											.attr("margin", current_margin_left_size);
									var inputObj = $("<input/>").val(obj.pk_marbasclass)
													.attr("type", "hidden")
													.attr("name", "pk_marbasclass_intree");
									var label = $("<label></label>").text(obj.name);
									var div = $("<div></div>")
											.addClass("tree_category5").append(a)
											.append(inputObj).append(label);
									childrenDiv.append(div);
								}
								childrenDiv.insertAfter(category_triggerObj.parent());
							 }else{
								 jQuery.ajax({
									 type : "POST",
										async : false,
										url : ebvp_context
												+ "/other/qryGoodsByPk?pk_marbasclass="
												+ pk_marbasclass  
												+ "&myts=" + myts,
										dataType : "text",
										data : "&" + formStr,
										success : function(result) {
									      var GoodsArr=eval(result);
									       for ( var loop = 0; loop < GoodsArr.length; loop++) {
												var obj = GoodsArr[loop];
												var prodPk = obj.pk_material;
												var prodName = obj.name;
												var inputObj = $("<input/>")
																.attr("type", "checkbox")
																.attr("id", "pk_material_intree")
																.attr("name", "pk_material_intree")
																.attr("pk_marbasclass", obj.pk_marbasclass)
																.attr("materialspec", obj.materialspec)
																.attr("materialtype", obj.materialtype)
																.attr("goodsClass_name", obj.goodsClass_name)
																.attr("main_unit_name", obj.main_unit_name)
																.attr("pk_main_unit", obj.pk_main_unit)
																.attr("numScale", obj.numScale)
																.attr("priceScale", obj.priceScale)
																.attr("planArriveDate", obj.planArriveDate)
																.val(obj.pk_material+"_"+obj.name)
																.addClass(obj.pk_material)
																.attr("style","margin-left:"+current_margin_left_size+"px;margin-top:4px");
												$(inputObj).click(function(){
													var checkValue = $(this).val();
													var checkProdPk = checkValue.substr(0,20);
													var checkProdName = checkValue.substr(21);
													if(this.checked){
														var checkBox = $("<input/>")
																		.attr("type", "checkbox")
																		.attr("pk_marbasclass", $(this).attr("pk_marbasclass"))
																		.attr("materialspec", $(this).attr("materialspec"))
																		.attr("materialtype", $(this).attr("materialtype"))
																		.attr("goodsClass_name", $(this).attr("goodsClass_name"))
																		.attr("main_unit_name", $(this).attr("main_unit_name"))
																		.attr("pk_main_unit", $(this).attr("pk_main_unit"))
																		.attr("numScale", $(this).attr("numScale"))
																		.attr("priceScale", $(this).attr("priceScale"))
																		.attr("planArriveDate", $(this).attr("planArriveDate"))
																		.val(checkValue)
																		.attr("style","margin-left:0px;px;margin-top:0px").attr("checked","checked");
														$(checkBox).click(function(){
															var checkValue = $(this).val();
															var checkProdPk = checkValue.substr(0,20);
															var checkProdName = checkValue.substr(21);
															var objs = $("."+checkProdPk);
															if(objs.length > 0){
																objs[0].checked = false;
															}
															$(this).parent().remove();
															var divHeight = $("#sel_prod")[0].offsetHeight;
													        var allChild = $("#sel_prod").children();
													        var lastChildHeight = allChild[allChild.length - 1].offsetTop;	
															
															//设置已选产品去高度
															var objDialogs = $(".ui-drop_dialog_content");
															var idxObj;
															for(idxObj=0;idxObj<objDialogs.length;idxObj++){
																var objDialog = $(objDialogs[idxObj]);
																if(objDialog.is(":visible")){
																	objDialog.attr("style","height:"+ lastChildHeight +"px");
																	break;
																}
															}
															$($(".border.lft")[idxObj]).attr("style","height:"+ lastChildHeight +"px");
															$($(".border.rit")[idxObj]).attr("style","height:"+ lastChildHeight +"px");
															$(".ui-drop_dialog_content").attr("style","height:"+ lastChildHeight +"px");
															$(".border.lft").attr("style","height:"+ lastChildHeight +"px");
															$(".border.rit").attr("style","height:"+ lastChildHeight +"px");
															$("#sel_prod").attr("style","height:"+ lastChildHeight +"px");
															
														});
														var labelProd = $("<label />").html(checkProdName)
														var div = $("<div></div>").attr("id", checkProdPk).attr("name", checkProdPk).attr("style", "float:left;display:inline").append(checkBox).append(labelProd);
														
														$("#sel_prod").append(div);;
													}else{
														
														$("#"+checkProdPk).remove();
													}													
													var allChild = $("#sel_prod").children();
													var lastChildHeight = allChild[allChild.length - 1].offsetTop;										
													$(".ui-drop_dialog_content").attr("style","height:"+ lastChildHeight +"px");
									                $(".border.lft").attr("style","height:"+ lastChildHeight +"px");
									                $(".border.rit").attr("style","height:"+ lastChildHeight +"px");
									                $("#sel_prod").attr("style","height:"+ lastChildHeight +"px");														
												});
												//查询该物料是否已经被选择
												var objProd = $("#"+obj.pk_material);
												if(objProd.length > 0){
													inputObj.attr("checked", "checked");
												}
												var label = $("<label></label>").text(obj.name + " " + obj.materialspec  + " " + obj.materialtype);
												var div = $("<div></div>")
														.addClass("tree_category5")
														.append(inputObj).append(label);
												childrenDiv.append(div);
								        }
									  	childrenDiv.insertAfter(category_triggerObj.parent());
									  	for ( var loop = 0; loop < GoodsArr.length; loop++) {
							        		var obj = GoodsArr[loop];
											var prodPk = obj.pk_material;
											var prodName = obj.name;
							        		
							        	}
								    }
								 })
							 }
						}
					});
					
					//自身展开后，将其兄弟节点及其子节点收缩回
					 category_triggerObj.parent(".tree_category5").siblings(".tree_category5").next(".children").slideUp(function(){
						 $(this).prev(".tree_category5").find(".category_trigger5").removeClass("close");
					 });

					return false;

				});
		$(".tree_btns5 .idBtnPicked").live('click', function() {
			var items = $("#sel_prod").find("[type='checkbox']");
			var maxNO = ($("#addGoodsListTable").find("tr").size() - 1) / 2; 
			var NO_increase = 1; // 序号增量
			for ( var loop = 0; loop < items.length; loop++) {
				var prodName = $(items[loop]).next("label").html();
				var pk_goods = $(items[loop]).val().substr(0,20);
				var pk_goodsClass = $(items[loop]).attr("pk_marbasclass");
				var materialspec = $(items[loop]).attr("materialspec");
				var materialtype = $(items[loop]).attr("materialtype");
				var goodsClass_name = $(items[loop]).attr("goodsClass_name");
				var main_unit_name = $(items[loop]).attr("main_unit_name");
				var pk_main_unit = $(items[loop]).attr("pk_main_unit");
				var numScale = $(items[loop]).attr("numScale");
				var priceScale = $(items[loop]).attr("priceScale");
				var planArriveDate = $(items[loop]).attr("planArriveDate");
				// 序号
				var current_NO = Math
						.floor(Math.random() * 10000000000000000000);// maxNO
																		// +
																		// NO_increase;
				NO_increase = NO_increase + 1;
				
//				var valid_date_id = "valid_date" + current_NO;

//				var invalid_date_id = "invalid_date"
//						+ current_NO;
                var main_amount_id="main_amount_"+current_NO;
                var advise_price_id="advise_price_"+current_NO;
                var storageOrg_name_id="storageOrg_name_"+current_NO;
				var plan_arrive_date_id="plan_arrive_date_"+current_NO;
				
				if ((maxNO + NO_increase) % 2 == 0) {
					var editRowFormStr = "<tr id='trid_"
							+ current_NO + "' class='contTr-even'>";														
							 
				} else {
					var editRowFormStr = "<tr id='trid_"
							+ current_NO + "' class='contTr-old'>";						
							
				}
				editRowFormStr += "<td style='font-size:12px;height: 12px;'>"+getLanMsg("0ec22410-000238")+goodsClass_name + "<input id='pk_goodsClass' name='pk_goodsClass'  type='hidden' value="+pk_goodsClass+"></br>";
//				editRowFormStr += "产品分类:"产品分类:
//					+ goodsClass_name + "</br>";"产品:""规格:"
				editRowFormStr += getLanMsg("0ec22410-000239")
					+ prodName + "<input id='pk_goods' name='pk_goods'  type='hidden' value="+pk_goods+"></br>";
				if(materialspec!=null&&materialspec!=""){
					editRowFormStr += getLanMsg("0ec22410-000240")
						+ materialspec + "</br>";
				}
				if(materialtype!=null&&materialtype!=""){
					editRowFormStr += getLanMsg("0ec22410-000241")
						+ materialtype+"</br>";					
				}
				//产品说明
				editRowFormStr +=getLanMsg("0ec22410-000247")+ "<input id='description' name='description' type='text' class='textfield pd_5x2px w_120px' style='float:None;height: 12px;;margin-top: 5px;margin-right: 5px;'>";
				editRowFormStr +="</td>";
				//数量单元格html，增加了非空提示
				editRowFormStr +="<td style='font-size:12px;height: 12px;margin-top: 5px;position:relative;' class='noclear'>";
				editRowFormStr +="<span>"+getLanMsg("0ec22410-000242")+"&nbsp;</span><br/>";
				editRowFormStr +="<input id='"+main_amount_id+"' name='main_amount'  type='text' value='' class='required textfield pd_5x2px w_66px' style='float:None;height: 12px;margin-top: 5px;margin-right: 5px;' onchange='subReduNum(this,"+numScale+")'/>";
				editRowFormStr +="<span style='margin-left:72px;'>"+main_unit_name+"</span>";
				editRowFormStr +="<input id='pk_main_unit' name='pk_main_unit' type='hidden' value='"+pk_main_unit+"'>";
				editRowFormStr +="<input id='numScale' name='numScale' type='hidden' value='"+numScale+"'>";
				editRowFormStr +="</td>";
				//建议价格单元格html，增加了非空提示
				editRowFormStr += "<td style='font-size:12px;height: 12px;margin-top: 5px;' class='noclear'>&nbsp;<input id='"+advise_price_id+"' name='advise_price'  type='text' class='required textfield pd_5x2px w_66px' style='float:None;height: 12px;margin-top: 5px;margin-right: 5px;' onchange='subReduNum(this,"+priceScale+")'><input id='priceScale' name='priceScale' type='hidden' value="+priceScale+"></td>"; 				
				
				editRowFormStr +="<td style='font-size:12px;height: 12px;margin-top: 5px;'>"+getLanMsg("0ec22410-000243")+"&nbsp;<input value=' *' id='"+storageOrg_name_id+"' name='storageOrg_name'  type='text' class='required textfield pd_5x2px w_128px' style='float:None;height: 12px;margin-top: 5px;color:red;'/><input id='pk_store_org' name='pk_store_org'  type='hidden'><br/>";						         
				editRowFormStr +=getLanMsg("0ec22410-000244")+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input id='storagehouse_name' name='storagehouse_name'  type='text' class='textfield pd_5x2px w_128px' style='float:None;height: 12px;margin-top: 5px;'/><input id='pk_storagehouse' name='pk_storagehouse'  type='hidden'> <br/>";
				editRowFormStr +=getLanMsg("0ec22410-000245")+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input id='goods_location' name='goods_location'  type='text' class='textfield pd_5x2px w_128px' style='float:None;height: 12px;margin-top: 5px;'/><input id='pk_goodslocation' name='pk_goodslocation'  type='hidden'></td>";				
				editRowFormStr +="<td style='font-size:12px;height: 12px;margin-top: 5px;margin-right: 5px;'>&nbsp;<input id='"+plan_arrive_date_id+"' name='plan_arrive_date'  type='text' value="+planArriveDate+" class='textfieldnew datepicker  pd_5x2px w_80px' style='float:None;height: 12px;margin-top: 5px;margin-right: 5px;'/></td> ";
				editRowFormStr += "<td style='font-size:12px;height: 12px;'><a class='linkstyle' id='deleterow' >"+getLanMsg("0ec22410-000246")+"</a></td>";
				editRowFormStr += "</tr>";
				//style='color:#3399cc;text-decoration:underline;' href='#'
			//	<input type='hidden' id='"+plan_arrive_date_id+"'>
				$('#addGoodsListTable').append(editRowFormStr);
				var trNode = "#trid_" + current_NO ;
		
				// 初始化 币种
				initCurrency(trNode);
				
//				$($(trNode).find("[name='storageOrg_name']")[0])
//					.UIDropDialogBank( {
//						'triggerClass' : "idTreePicker",
//						'content' : $("#storageOrgRowPicker")
//				});
//				
//				$($(trNode).find("[name='storagehouse_name']")[0])
//				.UIDropDialogBank( {
//					'triggerClass' : "idTreePicker",
//					'content' : $("#storageHouseRowPicker")
//			    });
//				
//				$($(trNode).find("[name='goods_location']")[0])
//				.UIDropDialogBank( {
//					'triggerClass' : "idTreePicker",
//					'content' : $("#goodsLocationRowPicker")
//			    });
//				
//				$($(trNode).find("[name='pur_org']")[0])
//				.UIDropDialogBank( {
//					'triggerClass' : "idTreePicker",
//					'content' : $("#purOrgRowPicker")
//			    });	

	            	
				$("#"+main_amount_id).UITipInside({
					   'required' : true
				});
				$("#"+advise_price_id).UITipInside({
					   'required' : true
				});
				//UITipInside组件会在input前后加上
				$(".noclear").find(".clear").remove();
			}
			
//			seajs.use(['$','jquery.ui.datepicker'],function($,datepicker){
//				$ = datepicker($);
//			});

			$(this).parents(".ui-drop_dialog").slideUp();
			return false;
		});
		
		$(".tree_btns5 .idBtnCancel").live('click', function(){
			$("#prod_filter").val("");
			$(this).parents(".ui-drop_dialog").slideUp();
			return false;
		})
	}
	
	// 初始化币种
	function initCurrency(trNode) {
		var myts = new Date();
		jQuery.ajax( {
			type : "GET",
			async : false,
			url : ebvp_context + "/prodprice/queryCurrency?myts=" + myts,
			dataType : "text",
			success : function(result) {
				var ele_pk_currency = $(trNode).find("[name='pk_currency']");
				if (result == 'NULL') {
					ele_pk_currency.empty();
				} else {

					var cnyValue = ele_pk_currency.val();
					var cnyArray = eval("(" + result + ")");
					ele_pk_currency.empty();
					for ( var index = 0; index < cnyArray.length; index++) {
						var obj = cnyArray[index];
						if (cnyValue == obj.pk_currtype) {
							ele_pk_currency.append("<option value='"
									+ obj.pk_currtype + "' selected>"
									+ obj.name + "</option>");
						} else {
							ele_pk_currency.append("<option value='"
									+ obj.pk_currtype + "'>" + obj.name
									+ "</option>");
						}
					}
				}
			}
		})
	}
	
	
	this.init = function(){
		addProdFunction();
		//初始化币种
		//initCurrency();
		
		//$("body").delegate("[name='plan_arrive_date']", "click", function() {
		//	showCalendar($(this).attr("id"), "y-mm-dd");
		//});	
		
		$("body").delegate("[name='main_amount']", "change", function() {
			   subReduNum($(this), $(this).next("input").next("input").val());
		});
		$("body").delegate("[name='advise_price']", "change", function() {
			   subReduNum($(this), $(this).next("input").val());
		});
		
	}
	
	//截去多余的小数位数或者补足小数位
	function subReduNum(obj,intPrecision){
		var value = trim(obj.val());
		obj.val(subReduNumPrivate(value,intPrecision)) ;
	}
	//删除左右两端的空格
	function trim(str){
		str = str + "";
		return str.replace(/(^\s*)|(\s*$)/g, "");
	}
	
	function subReduNumPrivate(strValue,intPrecision){
		if(isNaN(strValue)){
			return null;
		}
		if(strValue == null || strValue == ""){
			return null;
		}
		if (strValue.indexOf(".") != -1){
			var values = strValue.split(".");
			if(values[1].length > intPrecision){
				if(intPrecision > 0){
					strValue = values[0] + "." + values[1].substring(0,intPrecision);
					strValue = roundNum(strValue,values[1].substring(intPrecision),intPrecision);
				}else{
					strValue = values[0];
				}
			}else{
				for(var i=values[1].length;i<intPrecision;i++){
					strValue += "0";
				}
			}
		}else{
			if(intPrecision > 0){
				strValue += ".";
				for(var i=0;i<intPrecision;i++){
					strValue += "0";
				}
			}
		}
		return strValue;
	}
	
	function roundNum(oldValue,tailValue,intPrecision){
		var bAddOne = false;
		var numArray = new Array();
		for(var i=0;i<tailValue.length;i++){
			numArray[i] = tailValue.substring(i,i+1);
		}
		if(parseInt(numArray[0]) > 4){
			bAddOne = true;
		}else{
			for(var i=tailValue.length - 1;i>0;i--){
				if(parseInt(numArray[i]) > 4){
					numArray[i-1] = parseInt(numArray[i-1]) + 1;
				}
			}
			if(parseInt(numArray[0]) > 4){
				bAddOne = true;
			}
		}
		if(bAddOne){
			var strAddStr = "0.";
			for(var i=0;i<intPrecision;i++){
				if(i != intPrecision - 1){
					strAddStr = strAddStr + "0";
				}else{
					strAddStr = strAddStr + "1";
				}
			}
			oldValue = (parseFloat(oldValue) + parseFloat(strAddStr)) + "";
			if(oldValue.indexOf(".") != -1){
				var values = oldValue.split(".");
				oldValue = values[0] + "." + values[1].substring(0,intPrecision);
			}else {
				if(intPrecision > 0){
					oldValue += ".";
					for(var i=0;i<intPrecision;i++){
						oldValue += "0";
					}
				}
			}
		}
		return oldValue;
	}
	function len(s) { 
		var l = 0; 
		var a = s.split(""); 
		for (var i=0;i<a.length;i++) { 
			if (a[i].charCodeAt(0)<299) { 
				l++; 
			} else { 
				l+=2; 
			} 
		} 
		return l; 
	}
}


$(function() {
	var addGoodsApply = new AddGoodsApply();
	addGoodsApply.init();
	
});